package com.imooc.mall.controller;


import com.imooc.mall.common.ResultInfo;
import com.imooc.mall.common.ResultInfoUtil;
import com.imooc.mall.dto.LoginUser;
import com.imooc.mall.exception.MallException;
import com.imooc.mall.pojo.User;
import com.imooc.mall.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import static com.imooc.mall.common.MallConst.CURRENT_USER;
import static com.imooc.mall.enums.ResultEnum.NEED_LOGIN;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    IUserService userService;

    @PostMapping("/register")
    public ResultInfo<User> register(@RequestBody @Valid User user) {
        log.info("user register==>>{}", user.getUsername());
        return userService.register(user);

    }

    @PostMapping("/login")
    public ResultInfo<User> login(@RequestBody @Valid LoginUser user,
                                  HttpServletRequest request) {
        log.info("user login==>>{}", user.getUsername());
        ResultInfo<User> userResultInfo = userService.login(user.getUsername(), user.getPassword());
        //设置session
        HttpSession session = request.getSession();
        session.setAttribute(CURRENT_USER, userResultInfo.getData());
        log.info("用户登录 sessionId=>{}", session.getId());
        return userResultInfo;

    }

    //session保存再内存里，项目重启或者服务器重启就没了
    //方案：保存到redis,token+redis
    @GetMapping("/user")
    public ResultInfo<User> getUser(HttpServletRequest request) {
        log.info("查看用户sessionId=>{}", request.getSession().getId());
        User u = (User) request.getSession().getAttribute(CURRENT_USER);
        return ResultInfoUtil.withOutStatusSuccess(u);
    }

    /**
     * 登出功能
     *   session过期时间可以在appcation.yml配置，
     *   server:
     *   servlet:
     *     session:
     *       timeout: 120  单位为秒  （最小1分钟）
     * @param
     * @param request
     * @return
     */
    @PostMapping("/loginOut")
    public ResultInfo<User> loginOut(
            HttpServletRequest request) {
        log.info("查看用户sessionId=>{}", request.getSession().getId());
        request.getSession().removeAttribute(CURRENT_USER);
        return ResultInfoUtil.success();

    }
}
